import { useEffect, useRef } from 'react';

/**
 * 内联关键CSS并异步加载剩余样式表
 * @param {string} criticalCSS - 关键CSS内容
 * @param {string} fullCSSUrl - 完整CSS文件URL
 */
export const useCriticalCSS = (criticalCSS, fullCSSUrl) => {
  const loadedRef = useRef(false);

  useEffect(() => {
    // 创建style标签插入关键CSS
    const styleTag = document.createElement('style');
    styleTag.innerHTML = criticalCSS;
    document.head.appendChild(styleTag);

    // 异步加载完整CSS
    if (!loadedRef.current) {
      const linkTag = document.createElement('link');
      linkTag.rel = 'stylesheet';
      linkTag.href = fullCSSUrl;
      linkTag.onload = () => {
        // 加载完成后可移除关键CSS（可选）
        // document.head.removeChild(styleTag);
      };
      document.head.appendChild(linkTag);
      loadedRef.current = true;
    }

    return () => {
      document.head.removeChild(styleTag);
    };
  }, [criticalCSS, fullCSSUrl]);
};

/**
 * 预加载CSS资源
 */
export const preloadCSS = (url) => {
  const link = document.createElement('link');
  link.rel = 'preload';
  link.href = url;
  link.as = 'style';
  document.head.appendChild(link);
};

/**
 * 动态加载非关键CSS
 */
export const loadNonCriticalCSS = (url, media = 'all') => {
  const link = document.createElement('link');
  link.rel = 'stylesheet';
  link.href = url;
  link.media = 'print';
  link.onload = () => {
    link.media = media;
  };
  document.head.appendChild(link);
};
